import socket
import json
import struct

from dataTemp.temp import Mes


class Client:
    def __init__(self, host: str, port: int):
        self.host = host
        self.port = port
        self.sock = None

    def connect(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.connect((self.host, self.port))

    def send_message(self, message: Mes):
        if not self.sock:
            raise ConnectionError("Socket is not connected.")

        json_message = json.dumps(message.to_dict())
        message_length = len(json_message)
        print(f"发送消息{json_message}")
        self.sock.sendall(struct.pack('I', message_length))
        self.sock.sendall(json_message.encode('utf-8'))

    def receive_message(self):
        if not self.sock:
            raise ConnectionError("Socket is not connected.")

        length_buffer = self.sock.recv(4)
        message_length = struct.unpack('I', length_buffer)[0]
        data_buffer = self.sock.recv(message_length)
        json_message = data_buffer.decode('utf-8')
        return json_message

    def close(self):
        if self.sock:
            self.sock.close()
